import requests
import bs4
import re

def open_url(url):
    headers={'user-agent':'Mozilla/5.0'}

    res = requests.get(url,headers=headers)
    return res

def find_video(res):
    soups = bs4.BeautifulSoup(res.text,'html.parser')

    #名字
    titles=[]
    targets= soups.find_all("li",class_="video-item matrix")
    for each in targets:
        titles.append(each.a['title'])

    result=[]
    length=len(titles)
    for i in range(length):
        result.append(titles[i]+'\n')

    return result
def find_depth(res):
    soup = bs4.BeautifulSoup(res.text,'html.parser')
    depth = soup.find('li',class_='page-item last').text
    print(int(depth))
    return int(depth)

def main():
    host = "https://search.bilibili.com/all?keyword=%E5%96%9C%E6%B4%8B&from_source=web_search"
    res=open_url(host)
    depth= find_depth(res)

    result=[]
    for i in range(depth):
        if i==0:
            url = host
        else:
            url = host + '&page=' + str(i)
        res=open_url(url)
        result.extend(find_video(res))

    with open("Bili.txt","w",encoding='utf-8') as f:
        for each in result:
            f.write(each)

if __name__ == "__main__":
        main()
    
